package com.fruits.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fruits.common.Goods;
import com.fruits.common.GoodsImage;
import com.fruits.common.GoodsModel;
import com.fruits.common.Order;
import com.fruits.common.Shop;
import com.fruits.common.Tuan;
import com.fruits.constant.FruitsConstant;
import com.jfinal.core.Controller;
import com.jfinal.core.ModelUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.wx.exception.WxException;
import com.wx.util.WxMpUtil;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

public class WxShopController extends Controller {
	static Logger log = LoggerFactory.getLogger(WxShopController.class);

	public void info() throws WxException, WxErrorException {
		WxMpUser wxMpUser = authFromMp();
		Record shopRecord = Db.findFirst("select * from tbl_shop where openid=?", wxMpUser.getOpenId());
		if (shopRecord == null) {
			// 如果是店家 跳转到店家注册首页
			renderFreeMarker("/mobile/wxshop/wxshop_register.ftl");
		} else {
			setSessionAttr(FruitsConstant.WX_SHOP, shopRecord);
			if (shopRecord.getInt("enable") == 0) {
				renderFreeMarker("/mobile/wxshop/wxshop_active.ftl");
			} else {
				// 如果是店家 跳转到店家首页
				renderFreeMarker("/mobile/wxshop/wxshop_info.ftl");
			}
		}
	}

	// 店家注册
	public void register() throws WxException, WxErrorException {
		WxMpUser wxMpUser = authFromMp();
		new Shop().set("openid", wxMpUser.getOpenId()).set("enable", 0).set("isAdmin", 0).set("isDelete", 0).save();
		Record shopRecord = Db.findFirst("select * from tbl_shop where openid=?", wxMpUser.getOpenId());
		setAttr("shopRecord", shopRecord);
		renderFreeMarker("/mobile/wxshop/wxshop_active.ftl");
	}

	private WxMpUser authFromMp() throws WxException, WxErrorException {
		if (getSession().getAttribute(FruitsConstant.WX_USER) == null) {
			String appName = getPara("appName");
			String code = getPara("code");
			WxMpService wxMpService = WxMpUtil.getWxMpServiceByAppName(appName);
			WxMpUser wxMpUser = wxMpService.userInfo("oWxChswR0x2ksijzyKUFo2nGhwko", "zh_CN");

			// WxMpOAuth2AccessToken accessToken =
			// wxMpService.oauth2getAccessToken(code);
			// WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken,
			// "zh_CN");
			getSession().setAttribute(FruitsConstant.WX_USER, wxMpUser);
			getSession().setAttribute(FruitsConstant.APPNAME, appName);
		}
		return (WxMpUser) getSession().getAttribute(FruitsConstant.WX_USER);
	}

	private Record shopRecordFromSession() {
		return getSessionAttr(FruitsConstant.WX_SHOP);
	}

	public void listGoods() throws WxException, WxErrorException {
		String openid = authFromMp().getOpenId();
		int pageNumber = getParaToInt("page") == null ? 1 : getParaToInt("page");
		int pageSize = getParaToInt("rows") == null ? FruitsConstant.ROWS : getParaToInt("rows");
		Page<Record> page = Db.paginate(pageNumber, pageSize, "select g.id as goodsId,g.name as goodsName ",
				" from tbl_goods  g join  tbl_shop s on s.id=g.shopId where s.openid=? and g.isDelete=?",
				new Object[] { openid, 0 });
		setAttr("page", page);
		renderFreeMarker("/mobile/wxshop/wxshop_goods_list.ftl");
	}

	public void formGoods() {
		Goods goods = getModel(Goods.class, "goods");
		if (goods.get("id") != null) {
			goods = Goods.dao.findById(goods.get("id"));
			setAttr("goods", goods);
			List<GoodsModel> gmList = GoodsModel.dao.find("select * from tbl_goods_model where goodsId=?",
					new Object[] { goods.get("id") });
			if (gmList != null && gmList.size() > 0) {
				setAttr("gmList", gmList);
			}
			List<GoodsImage> imageList = GoodsImage.dao.find(
					"select * from tbl_goods_image where goodsId=? order by id ", new Object[] { goods.get("id") });
			if (imageList != null && imageList.size() > 0) {
				setAttr("imageList", imageList);
			}
		}
		renderFreeMarker("/mobile/wxshop/wxshop_goods_insert.ftl");
	}

	public void saveGoods() {
		// 保存商品信息
		List<GoodsImage> imageList = new ArrayList<GoodsImage>();
		for (UploadFile tmp : getFiles()) {
			File file = (copyFile(tmp.getFile(), shopRecordFromSession().get("id").toString(), "goods"));
			GoodsImage image = new GoodsImage();
			image.set("url", "/upload/" + shopRecordFromSession().get("id").toString() + "/goods/" + file.getName())
					.set("filePath", file.getAbsolutePath());
			imageList.add(image);
		}
		Goods goods = getModel(Goods.class, "goods");
		goods.set("shopId", shopRecordFromSession().get("id"));
		boolean isSaved = goods.save();
		List<GoodsModel> goodsModelList = ModelUtils.batchInjectModel(getRequest(), GoodsModel.class, "goodsModel");
		// 保存商品model信息
		if (isSaved && goods.get("id") != null) {
			for (GoodsModel gm : goodsModelList) {
				gm.set("goodsId", goods.get("id"));
			}
			GoodsModel.dao.batchSave(goodsModelList);
		}
		if (isSaved && goods.get("id") != null) {
			for (GoodsImage gi : imageList) {
				gi.set("goodsId", goods.get("id"));
			}
			GoodsImage.dao.batchSave(imageList);
		}
		// 保存商品图片信息
		forwardAction("/mobile/wxshop/listGoods");
	}

	// 商品如果正在团购中，不能修改
	public void updateGoods() {
		Goods goods = getModel(Goods.class, "goods");
		boolean isUpdated = goods.update();
		if (isUpdated) {
			// 删除旧的

		}
		forwardAction("/mobile/wxshop/listGoods");
	}

	public void deleteGoods() {
		String goodsId = getPara("goods.id");
		Db.update("update tbl_goods set isDelete=? where id=?", new Object[] { 1, goodsId });
		forwardAction("/mobile/wxshop/listGoods");
	}

	private void listAllGoods() throws WxException, WxErrorException {
		String openid = authFromMp().getOpenId();
		String sql = "select g.id as goodsId ,g.name as goodsName from tbl_goods g join tbl_shop s on g.shopId=s.id where g.isDelete=? and s.openid=?";
		setAttr("allGoods", Db.find(sql, new Object[] { 0, openid }));
	}

	public void listTuan() throws WxException, WxErrorException {
		String openid = authFromMp().getOpenId();
		int pageNumber = getParaToInt("page") == null ? 1 : getParaToInt("page");
		int pageSize = getParaToInt("rows") == null ? FruitsConstant.ROWS : getParaToInt("rows");
		Page<Record> page = Db.paginate(pageNumber, pageSize,
				"select g.id as tuanId ,g.title as tuanTitle,g.remark as tuanRemark ",
				" from tbl_tuan  g join  tbl_shop s on  s.id=g.shopId  where  s.openid=? and g.isDelete=?",
				new Object[] { openid, 0 });
		setAttr("page", page);
		renderFreeMarker("/mobile/wxshop/wxshop_tuan_list.ftl");
	}

	public void formTuan() throws WxException, WxErrorException {
		Tuan tuan = getModel(Tuan.class, "tuan");
		listAllGoods();
		if (tuan.get("id") != null) {

		}
		renderFreeMarker("/mobile/wxshop/wxshop_tuan_insert.ftl");
	}

	public void saveTuan() {
		Tuan tuan = getModel(Tuan.class, "tuan");
		tuan.set("shopId", shopRecordFromSession().get("id"));
		// 复制商品数据
		boolean isSaved = tuan.save();

		forwardAction("/mobile/wxshop/listTuan");
	}

	public void listOrder() throws WxException, WxErrorException {
		String openid = authFromMp().getOpenId();
		int pageNumber = getParaToInt("page") == null ? 1 : getParaToInt("page");
		int pageSize = getParaToInt("rows") == null ? FruitsConstant.ROWS : getParaToInt("rows");
		Page<Record> page = Db.paginate(pageNumber, pageSize, "select * ",
				" from tbl_order  g join  tbl_shop s on  s.id=g.shopId where s.openid=? and g.isDelete=?",
				new Object[] { openid, 0 });
		setAttr("page", page);
		renderFreeMarker("/mobile/wxshop/wxshop_order_list.ftl");
	}

	public void formOrder() {
		Order order = getModel(Order.class, "order");
		if (order.get("id") != null) {

		}
	}

	/**
	 * 复制单个文件
	 * 
	 * @param oldPath
	 *            String 原文件路径 如：c:/fqf.txt
	 * @param newPath
	 *            String 复制后路径 如：f:/fqf.txt
	 * @return boolean
	 */
	public File copyFile(File oldfile, String shopId, String type) {
		InputStream in = null;
		FileOutputStream fs = null;
		File newFile = null;
		try {
			if (oldfile.exists()) { // 文件存在时
				int bytesum = 0;
				int byteread = 0;
				in = new FileInputStream(oldfile); // 读入原文件
				StringBuffer newPathSb = new StringBuffer();
				newPathSb.append(oldfile.getParent());
				newPathSb.append(File.separator);
				newPathSb.append(shopId);
				newPathSb.append(File.separator);
				newPathSb.append(type);
				newPathSb.append(File.separator);
				newPathSb.append(
						System.currentTimeMillis() + oldfile.getName().substring(oldfile.getName().lastIndexOf(".")));
				newFile = new File(newPathSb.toString());
				if (!newFile.getParentFile().exists()) {
					newFile.getParentFile().mkdirs();
				}
				if (!newFile.exists()) {
					newFile.createNewFile();
				}
				fs = new FileOutputStream(newFile);
				byte[] buffer = new byte[1444];
				while ((byteread = in.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				in.close();
				fs.close();
				oldfile.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (fs != null) {
					fs.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return newFile;
	}

}
